#!/usr/bin/python3

##-image combining by liuqimin
import os
from PIL import Image
import copy
import re

#-----------------------
def combine(img_list):
    widths = []
    heights = []
    for img in img_list:
        image1 = Image.open(img)
        widths.append(image1.size[0])
        heights.append(image1.size[1])

    w = max(widths)
    h = sum(heights)

    new_im = Image.new(mode='L', size=(w, h), color=255)

    for i in range(0, len(img_list)):
        image1 = Image.open(img_list[i])
        if i == 0:
            new_im.paste(image1, (0, 0))
        else:
            new_im.paste(image1, (0, sum(heights[0:i])))

    return new_im
#-----------combine images files contain underline ('_')----------------------------
def ProcessUnderline(path):

    file_list = set(os.listdir(path))
    flist = copy.deepcopy(file_list)
    ##---first, processing files with '_'-------------
    xx = 0
    for f in file_list:
        print('processing ', f)
        x = f.find('_')
        if x == -1:
            continue
        print('f=', f)
        xx = xx + 1

        if not f in flist:  ####has been removed already
            continue
        y = f.rfind('.')
        lst = []
        tt = f[:x] + f[y:]
        print('tt=', tt)
        if tt in file_list:
            lst.append(tt)
            flist.remove(tt)
        for i in range(1, 100):
            tt = f[:x + 1] + str(i) + f[y:]
            if tt in flist:
                lst.append(os.path.join(path, tt))
                flist.remove(tt)
            else:
                break
        if lst != []:
            print('lst=', lst)
            img = combine(lst)
            img.save(os.path.join(path, f[:x] + f[y:]))
    # ------------------------------


##------------------main-----------------------
path='D:\\松鼠搜题\\最终版\\微积分-第二版-吴传生\\data'
#out_path='d:\\临时图书\\out'
if os.path.exists(path):
    ProcessUnderline(path)

#----copy files to output path （可以暂时不做）
# for f in os.listdir(path):
#     if '_' in f:
#         continue
#     xx=os.path.join(path, f)
#     tt=os.path.join(out_path, f)
#
#     os.system('copy '+ xx+ ' '+tt)